#ifndef DATABASE_CONNECTION_H
#define DATABASE_CONNECTION_H
#include <string>
#include "Service.h"
#include "service_handler.h"
#include "connection_handler.h"
#include "dl_protocol.h"
using namespace std;
using namespace std::tr1;
class ClientConnection;
struct DatabaseRequest;
struct CMD_Head;

class ClientConnectionHandler {
public:
	virtual void onClientConnected(ClientConnection* conn) = 0;
	virtual void onClientData(ClientConnection* conn, int mainCmd, int subCmd, void* data, int len) = 0;
	virtual bool onClientDisconnected(ClientConnection* conn) = 0;
};

class ClientConnection : public ConnectionHandler, public ServiceHandler {
public:
	void init(Service* service, std::string ip, int port);
	void init(Service* service, Connection* conn);
	void close();
	void setHandler(ClientConnectionHandler* handler);
	void sendDBData(int mainCmd, int subCmd, void* data, int len);
	bool SendData(int8_t wMainCmdID, int8_t wSubCmdID, void* pData, int wDataSize);
	void setUserData(void* userData);
	void* getUserData();
private:
	virtual void handleCommand(std::string cmd, void* data);
	virtual void onConnected(Connection*);
	virtual void onClose(Connection*);	
	virtual void onData(Connection* conn);

	void onCmdHead(CMD_Head* header);	
	bool SendData(int8_t wMainCmdID, int8_t wSubCmdID);
	bool SendBuffer(void * pBuffer, int wSendSize);

	string m_ip;
	int m_port;
	Service* m_service;
	Connection* m_connection;
	ClientConnectionHandler* m_handler;
	
	int m_currentId;

	bool isRecv;
	bool m_connected;
	void* m_userData;
};
#endif //DATABASE_CLIENT_H